package com.funny.stock.user.service;

import com.funny.stock.base.service.BaseCrudService;
import com.funny.stock.base.util.PropertiesCopyUtil;
import com.funny.stock.user.dao.pojo.UserInfoDO;
import com.funny.stock.user.dao.repo.UserInfoRepo;
import com.funny.stock.user.util.StockPasswordEncoder;
import com.funny.stock.user.vo.SysUserVO;
import com.funny.stock.user.vo.UserInfoVO;
import com.funny.stock.user.vo.UserRegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Description  
 * @Author  pengl
 * @Date 2020-05-17 
 */

@Service
public class UserInfoService extends BaseCrudService<UserInfoDO,Long> {

	@Autowired
	UserInfoRepo repository;

	@Autowired
	SysUserService sysUserService;

	@Autowired
	SysRoleService sysRoleService;

	protected JpaRepository<UserInfoDO, Long> setupJpaRepository() {
		return repository;
	}

	@Transactional
	public SysUserVO registerUser(UserRegisterVO registerVO){
		StockPasswordEncoder passwordEncoder = new StockPasswordEncoder();
		String encodePwd = passwordEncoder.encode(registerVO.getPassword());

//		SysRoleDO sysRoleDO = sysRoleService.findByName("普通用户");
		UserInfoDO userInfoVO = new UserInfoDO();
		userInfoVO.setName(registerVO.getUsername());
		UserInfoDO infoDO = save(userInfoVO);


		SysUserVO sysUserVO = new SysUserVO();
		sysUserVO.setActive(1);
		sysUserVO.setRoleId(1L);
		sysUserVO.setLoginAccount(registerVO.getUsername());
		sysUserVO.setPassword(encodePwd);
		sysUserVO.setCreateTime(new Date());
		sysUserVO.setUserId(infoDO.getId());
		SysUserVO save = sysUserService.save(sysUserVO);

		return save;
	}

	@Transactional
	public UserInfoDO updateUser(Long userId,UserInfoVO userInfoVO){
		UserInfoDO userInfoDO = PropertiesCopyUtil.copyProperties(userInfoVO, UserInfoDO.class);
		userInfoDO.setId(userId);
		return save(userInfoDO);
	}

}
